﻿using System;
using System.Xml;
using System.ServiceModel;
using System.ServiceModel.Description;
using TipokHostContract;

namespace TipokHostManager
{
    class InitializerWCFService
    {
        private static ServiceHost hostERCH = null;//通讯服务宿主

        public static void Start()
        {
            WcfServicesStart();
        }

        public static void Stop()
        {
            WcfServicesStop();
        }

        /// <summary>
        /// 启动wcf服务
        /// </summary>
        /// <param name="args"></param>
        private static void WcfServicesStart()
        {
            ////CommunicateServices
            hostERCH = new ServiceHost(typeof(HostServiceStrategy));
            //#if DEBUG
            ServiceMetadataBehavior smb = hostERCH.Description.Behaviors.Find<ServiceMetadataBehavior>();
            if (smb == null)
            {
                smb = new ServiceMetadataBehavior();
                hostERCH.Description.Behaviors.Add(smb);
            }
            smb.HttpGetUrl = new Uri("http://localhost:8080/host/");
            smb.HttpGetEnabled = true;
            //#endif
            //增加设置配额限制
            ServiceThrottlingBehavior stb = hostERCH.Description.Behaviors.Find<ServiceThrottlingBehavior>();
            if (stb == null)
            {
                stb = new ServiceThrottlingBehavior();
                hostERCH.Description.Behaviors.Add(stb);
            }
            stb.MaxConcurrentCalls = 8000;
            stb.MaxConcurrentSessions = 8000;
            stb.MaxConcurrentInstances = 8000;
            Uri _uri = new Uri("net.pipe://localhost/host/");
            hostERCH.AddServiceEndpoint(typeof(IContractServiceStrategy), new NetNamedPipeBinding()
            {
                MaxBufferSize = 2147483647,
                MaxConnections = 8000,
                MaxReceivedMessageSize = 2147483647,
                ReceiveTimeout = new TimeSpan(0, 10, 0),
                CloseTimeout = new TimeSpan(0, 10, 0),
                SendTimeout = new TimeSpan(0, 10, 0),
                OpenTimeout = new TimeSpan(0, 10, 0),
                TransferMode = TransferMode.Buffered,
                ReaderQuotas = new XmlDictionaryReaderQuotas() { MaxStringContentLength = 2147483647 },
                Security = new NetNamedPipeSecurity() { Mode = NetNamedPipeSecurityMode.None }
            }, _uri);
            hostERCH.Open();
        }

        /// <summary>
        /// 关闭wcf服务
        /// </summary>
        private static void WcfServicesStop()
        {
            try
            {
                hostERCH.Close();
            }
            catch
            {
                hostERCH.Abort();
            }
            hostERCH = null;
        }
    }
}
